#ifndef TCP_SERVER
#define TCP_SERVER

#include <ctime>
#include <iostream>
#include <string>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <vector>
#include "Connection_End.hpp"

using boost::asio::ip::tcp;
const std::string WelcomeMessage =  "1234512345";
const std::string WelcomeMessage2 = "FiveCharss";
int m_connectionID;

class Tcp_Server
{

	tcp::acceptor acceptor_;
	std::vector<Connection_End::ConnectionEndPointer > m_Connections;


public:
	Tcp_Server(boost::asio::io_service& io_service, int Port ): acceptor_(io_service, tcp::endpoint(tcp::v4(), Port ))
	{
		std::cout<<"Tcp_Server constructor "<<std::endl;
		start_accept();
		m_connectionID = 0 ;

	};

private:
	void start_accept()
	{

		std::cout<<"Entering Start_accept"<<std::endl;
		std::cout<<"start_accept:at entry  m_connectionID "<<m_connectionID<<std::endl;

//		while( true )
//		{
		Connection_End::ConnectionEndPointer new_connection( new Connection_End( acceptor_.get_io_service() , m_connectionID++ ) );
		std::cout<<"start_accept: m_connectionID "<<m_connectionID<<std::endl;
//		Connection_End::ConnectionEndPointer new_connection = new Connection_End( acceptor_.get_io_service() );		
//		acceptor_.async_accept(	new_connection->socket() ,	boost::bind(&Tcp_Server::handle_accept,
//															this,
//																new_connection,
//															boost::asio::placeholders::error) );


		acceptor_.async_accept(	new_connection->socket() , boost::bind(&Tcp_Server::handle_accept,
										    this,
											new_connection,
											boost::asio::placeholders::error) );

//			acceptor_.accept(  new_connection->socket() );
//			std::cout<<"Connection Accepted from  remote client !"<<std::endl;
//			new_connection->start();
//		}

		std::cout<<"Leaving Start_accept"<<std::endl;
	}

	void handle_accept( Connection_End::ConnectionEndPointer new_connection,
						const boost::system::error_code& error   )
	{

		//Add connection to the list of connections
		if (!error)
		{
			std::cout<<"Connection Accepted from  remote client on connection ID:"<<m_connectionID<<std::endl;
			new_connection->start();
			m_Connections.push_back( new_connection );
		}
		start_accept();
	}


};
#endif
